package com.free.picture.ecognition.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.free.common.core.web.domain.R;
import com.free.picture.ecognition.pojo.xfyun.AudioUploadResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileNotFoundException;
import java.nio.charset.StandardCharsets;
import java.security.SignatureException;

import static com.free.picture.ecognition.xfyun.Ifasrdemo.getResult;
import static com.free.picture.ecognition.xfyun.Ifasrdemo.upload;

@RestController()
@RequestMapping("/xfAudio")
public class AudioController {
    private static final String TEM_FILE_PATH = "/audio/temp.file";

    @PostMapping("uploadAudioFile")
    public R<String> uploadAudioFile(@RequestBody  String fileUrl) {
        try {
            byte[] decode = Base64.decode(fileUrl.getBytes(StandardCharsets.UTF_8));
            File file = new File(TEM_FILE_PATH);
            HttpUtil.downloadFile("192.168.2.77"+new String(decode,StandardCharsets.UTF_8), file);
            String result = upload(file);
            return R.ok(JSONUtil.toBean(result, AudioUploadResult.class).getContent().getOrderId());
        } catch (SignatureException | FileNotFoundException e) {
            e.printStackTrace();
        }
        return R.fail();
    }
    @PostMapping("getContent")
    public R getContent(@RequestBody String orderId) {
        String result;
        try {
            result = getResult(orderId);
            return R.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.fail();
    }

}
